package com.znzz.course.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
import com.znzz.course.entity.Course;
import com.znzz.course.entity.Student;
import com.znzz.course.util.ConnByHttp;
import com.znzz.course.util.db.CourseDao;
import com.znzz.course.util.db.DBManager;
import com.znzz.course.util.db.DataBaseHelper;
import com.znzz.course.R;
import com.znzz.course.util.db.StudentDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 主界面----课程表功能模块
 * 背景更换目前只能选择head里面的图片
 * 做的时候没有使用fragment，导致做的很麻烦，效果是一样的
 */
public class MainActivity extends AppCompatActivity {
    //当前头像
    private de.hdodenhof.circleimageview.CircleImageView icon;
    //背景ImageView
    private ImageView background;
    // 头像Bitmap
    private Bitmap head;
    //背景Bitmap
    private Bitmap backgroundImage;
    // private static String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/kcb";
    // sd路径
    private static String head_path = "sdcard/myHead/";
    private static String backgroundImagePath = "sdcard/myBackground/";
    //滑动菜单
    private DrawerLayout mDrawerLayout;
    //星期几
    private RelativeLayout day;
    //当前日期
    protected TextView dateTextView;
    //toast事件
    public static Toast mToast;
    //定时调度机制
    private ScheduledExecutorService scheduledExecutorService;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    public String studentId;

    Handler handler1, handler2;
    Student student = new Student();

    //底部的三个跳转应用，图片和图框
    private ImageView imageView1, imageView2, imageView3;
    private LinearLayout layout1, layout2, layout3;

    public MainActivity() {
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取登陆传递过来的值
        Intent intent = getIntent();
        studentId = intent.getStringExtra("studentId");
        //异步通信，传递回来的数据----》json
        //学生信息处理
        handler2 = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        //将返回的content数据分析封装到Student类中
                        String content = msg.obj.toString();
                        JSONObject jsonObject;
                        String result = "";
                        //保存学生信息到本地数据库中
                        StudentDao studentDao = new StudentDao(MainActivity.this);
                        if (studentDao.loadData() != null) {
                            studentDao.deleteStudent();
                        }
                        try {
                            jsonObject = new JSONObject(content);
                            result = jsonObject.getString("result");
                            String major = jsonObject.getString("major");
                            String collage = jsonObject.getString("collage");
                            jsonObject = new JSONObject(jsonObject.getString("student"));
                            student = new Student();
                            student.setStudentId(jsonObject.getString("studentId"));
                            student.setName(jsonObject.getString("name"));
                            student.setPassword(jsonObject.getString("password"));
                            student.setSex(jsonObject.getString("sex"));
                            student.setClazzId(jsonObject.getString("clazzId"));
                            student.setMajor(major);
                            student.setPhone(jsonObject.getString("phone"));
                            student.setCollage(collage);
//                            System.out.println("student="+student.getName().toString());
                            studentDao.saveData(student);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (result.equals("T")) {
                            Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        };

        //初始化课表内容
        handler1 = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        //从后端数据库导入课表
                        String result = msg.obj.toString();
                        if (!result.equals("")) {
                            CourseDao courseDao = new CourseDao(MainActivity.this);
                            if (courseDao.loadData() != null) {
                                courseDao.deleteAllCourse();
                            }
                            try {
                                JSONObject jsonObject1 = new JSONObject(result);
                                JSONArray jsonArray = jsonObject1.getJSONArray("courses");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                                    Course course = new Course();
                                    course.setClassEnd(Integer.parseInt(jsonObject.getString("clazzEnd")));
                                    course.setClassRoom(jsonObject.getString("clazzRoom"));
                                    course.setClassStart(jsonObject.getInt("clazzStart"));
                                    course.setCourseName(jsonObject.getString("courseId"));
                                    course.setDay(jsonObject.getInt("day"));
                                    course.setTeacher(jsonObject.getString("teacherId"));
                                    course.setWeekEnd(jsonObject.getInt("weekEnd"));
                                    course.setWeekStart(jsonObject.getInt("weekStart"));
                                    //存储数据到数据库
                                    courseDao.saveData(course);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //从数据库读取数据
                            ArrayList<Course> coursesList = courseDao.loadData();
                            //使用从数据库读取出来的课程信息来加载课程表视图
                            for (Course course : coursesList) {
                                createCourseView(course);
                            }
                            Toast.makeText(MainActivity.this, "导入成功", Toast.LENGTH_LONG).show();
//                            finish();
                        } else {
                            Toast.makeText(MainActivity.this, "导入失败", Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        };

        //底部选择---》各个部分之间的跳转
        layout1 = findViewById(R.id.layout1);
        layout2 = findViewById(R.id.layout2);
        layout3 = findViewById(R.id.layout3);
        //我的页面
        layout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyInformationActivity.class);
                intent.putExtra("studentId", new StudentDao(MainActivity.this).loadData().getStudentId());
                startActivity(intent);
            }
        });
////        首页面
//        layout1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this,IndexActivity.class);
//                intent.putExtra("studentId",student.getStudentId());
//                startActivity(intent);
//            }
//        });

        //左边侧滑菜单
        mDrawerLayout = (DrawerLayout) findViewById(R.id.draw);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
        //工具条
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        navView.setCheckedItem(R.id.score);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    //添加课程
                    case R.id.add_courses:
                        Intent intent = new Intent(MainActivity.this, AddCourseActivity.class);
                        startActivityForResult(intent, 0);
                        break;
                        //关于我们信息页面
                    case R.id.menu_about:
                        Intent intent1 = new Intent(MainActivity.this, AboutActivity.class);
                        startActivity(intent1);
                        break;
                        //导入课程信息--》跳转到导入页面
                    case R.id.leading_in:
//                        LayoutInflater inflater = LayoutInflater.from(getApplication());
//                        View view = inflater.inflate(R.layout.activity_term_choice,null);
//                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//                        builder.setView(view);
//                        AlertDialog dialog = builder.create();
//                        dialog.show();
//                        dialog.getWindow().setLayout(300,300);
                        Intent intent3 = new Intent(MainActivity.this, TermChoiceActivity.class);
                        startActivity(intent3);
//                        initialize();
                        break;
                        //绑定信息---》将学号和电话号码进行绑定
                    case R.id.binding:
                        Intent intent4 = new Intent(MainActivity.this, BindingInformationActivity.class);
//                        startActivity(intent4);
                        startActivityForResult(intent4,1);
                        break;
                        //修改课程表页面的背景图片
                    case R.id.modify_background:
                        showBTypeDialog();
                        break;
                    default:
                        System.out.println("错误");
                }
                mDrawerLayout.closeDrawers();
                return true;
            }
        });

        //创建课程表左边视图(节数)
        createLeftView();

        //从数据库读取数据---》存入本地数据库的
        ArrayList<Course> coursesList = new CourseDao(MainActivity.this).loadData();
        //使用从数据库读取出来的课程信息来加载课程表视图
        for (Course course : coursesList) {
            createCourseView(course);
        }

        //获取系统时间
        dateTextView = (TextView) navView.getHeaderView(0).findViewById(R.id.Menu_main_textDate);
        //获取头像
        icon = (de.hdodenhof.circleimageview.CircleImageView) navView.getHeaderView(0).findViewById(R.id.icon_image);
        background = findViewById(R.id.bg);
        //初始化日期与头像
        initDate();
        //相机拍摄不成功时，加上这三行代码
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    //创建课程节数视图---一天12节课显示
    private void createLeftView() {
        for (int i = 1; i < 12; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.left_view, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(110, 180);
            view.setLayoutParams(params);
            TextView text = view.findViewById(R.id.class_number_text);
            text.setText(String.valueOf(i));
            LinearLayout leftViewLayout = findViewById(R.id.left_view_layout);
            leftViewLayout.addView(view);
        }
    }


    //创建课程视图
    public void createCourseView(final Course course) {
        //获取视图效果
        final int[] course_bj = {R.drawable.coursetable1, R.drawable.coursetable2,
                R.drawable.coursetable3, R.drawable.coursetable4, R.drawable.coursetable5,
                R.drawable.coursetable6, R.drawable.coursetable7, R.drawable.coursetable8,
                R.drawable.coursetable9, R.drawable.coursetable10};
        int height = 180;
        //获取课程在星期几
        int getDay = course.getDay();
        if ((getDay < 1 || getDay > 7) || course.getClassStart() > course.getClassEnd() || course.getClassEnd() > 12 || course.getWeekStart() > course.getWeekEnd()) {
            if (mToast == null) {
                mToast = Toast.makeText(this, "输入错误，请重新输入", Toast.LENGTH_SHORT);
            } else {
                mToast.setText("输入错误，请重新输入");
                mToast.setDuration(Toast.LENGTH_SHORT);
            }
            mToast.show();
        } else {
            switch (getDay) {
                case 1:
                    day = findViewById(R.id.monday);
                    break;
                case 2:
                    day = findViewById(R.id.tuesday);
                    break;
                case 3:
                    day = findViewById(R.id.wednesday);
                    break;
                case 4:
                    day = findViewById(R.id.thursday);
                    break;
                case 5:
                    day = findViewById(R.id.friday);
                    break;
                case 6:
                    day = findViewById(R.id.saturday);
                    break;
                case 7:
                    day = findViewById(R.id.weekday);
                    break;
            }
            final View v = LayoutInflater.from(this).inflate(R.layout.course_card, null); //加载单个课程布局
            //设置开始高度,即第几节课开始
            v.setY(height * (course.getClassStart() - 1));
            //处理课程高度
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                    (ViewGroup.LayoutParams.MATCH_PARENT,
                            (course.getClassEnd() - course.getClassStart() + 1) * height - 8);
            //设置布局高度
            v.setLayoutParams(params);
            //显示课程名字和教室
            TextView text = v.findViewById(R.id.text_view);
            text.setBackgroundResource(course_bj[(int) (Math.random() * 10)]);
            text.setText(course.getCourseName() + "\n\n" + course.getClassRoom()); //显示课程名
            day.addView(v);
            //长按删除课程
            v.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    v.setVisibility(View.GONE);
                    day.removeView(v);//再移除课程视图
                    new CourseDao(MainActivity.this).deleteCourse(course);
                    return true;
                }
            });
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, MessageCourseActivity.class);
                    intent.putExtra("course", course);
                    startActivity(intent);
                }
            });
        }
    }

    //回调函数（如今需要从A的界面跳转到B（C）的界面执行相应的操作。操作执行完毕之后，从B（C）的界面跳转回A的界面，或许还会返回一些数据交给A处理）
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果--背景
            case 1:
                if (resultCode == RESULT_OK) {
                    cropBackground(data.getData());// 裁剪图片
                }
                break;
            //调用系统裁剪图片后---背景
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        setPicToView(head);// 保存在SD卡中
                        ImageView imageView = findViewById(R.id.bg);
                        imageView.setImageBitmap(head);
                    }
                }
                break;
            //调用拍摄功能
            case 3:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropBackground(Uri.fromFile(temp));// 裁剪图片
                }
                break;

            //及时刷新备注更改的信息
            case 4:
                CourseDao courseDao = new CourseDao(MainActivity.this);
                //从数据库读取数据
                ArrayList<Course> coursesList = courseDao.loadData();
                //创建课程表左边视图(节数)
                createLeftView();
                //使用从数据库读取出来的课程信息来加载课程表视图
                for (Course course : coursesList) {
                    createCourseView(course);
                }
                break;
            default:
                break;
        }
        switch (resultCode){
            case 0:
                if (data.getSerializableExtra("course").equals("no"))
                    return;
                Course course = (Course) data.getSerializableExtra("course");
                //创建课程表视图
                createCourseView(course);
                //存储数据到数据库
                CourseDao courseDao = new CourseDao(MainActivity.this);
                courseDao.saveData(course);
                break;
            case 1:
                String msg = data.getStringExtra("msg");
                if (msg.equals("no")){
                    return;
                }
                StudentDao studentDao = new StudentDao(MainActivity.this);
                String id = studentDao.loadData().getStudentId();
                String url =
                        "http://192.168.92.1:8123/courseServer/getByStudentId?studentId=" + id;
                //启动子线程
                ConnByHttp connByHttp = new ConnByHttp(url, handler2);
                connByHttp.start();
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //课表添加
    public void test_click(View v) {
        Intent intent5 = new Intent(MainActivity.this, AddCourseActivity.class);
        startActivityForResult(intent5, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }

    @SuppressLint("SimpleDateFormat")
    private void initDate() {
        Date currentTime = new Date();
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        //指定需要获取的时间点
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentTime);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日  ");
        String dateString = formatter.format(currentTime);
        dateTextView.setText(dateString + "星期" + weekDays[w]);
    }

    //修改头像---》跳转到我的页面进行修改图片
    public void change_image(View v) {
        Intent intent = new Intent(MainActivity.this, MyInformationActivity.class);
        startActivity(intent);
    }

    //通过change_user_image页面获取改变按钮，实现操作，背景
    private void showBTypeDialog() {
        //对话框---弹出选择图库的按钮
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        final View change = LayoutInflater.from(this).inflate(R.layout.change_user_image, null);
        TextView select_gallery = (TextView) change.findViewById(R.id.select_gallery);
        //change_user_image
        select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
                Intent background = new Intent(Intent.ACTION_PICK, null);
                //打开系统相册，获取图片进行扫描操作
                background.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(background, 1);
                dialog.dismiss();
            }
        });
        dialog.setView(change);
        //显示视图
        dialog.show();
    }

    //调用系统的裁剪功能---背景
    public void cropBackground(Uri uri) {
//        设置图片的参数
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 960);
        intent.putExtra("aspectY", 1706);
        // outputX outputY 是裁剪图片宽高    -------main(960,1706)
        intent.putExtra("outputX", 960);
        intent.putExtra("outputY", 1706);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    //将传递的数据保存到SD卡中
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        String fileName;
            File file = new File(backgroundImagePath);
            file.mkdirs();// 创建文件夹
            fileName = backgroundImagePath + "bg.jpg";

        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //初始化课表信息
    public void initialize(String studentId, String semester) {
        Intent intent = getIntent();
        studentId = intent.getStringExtra("studentId");
        //防止跳转之后参数重置，这时候去导入课表为空
        if (studentId == null || studentId == "") {
            StudentDao studentDao = new StudentDao(MainActivity.this);
            studentId = studentDao.loadData().getStudentId();
        }
        String url =
                "http://192.168.92.1:8123/courseServer/getCourseByStudentId?studentId=" + studentId + "&semesterId=" + semester;
        //启动子线程
        ConnByHttp connByHttp = new ConnByHttp(url, handler1);
        connByHttp.start();
    }
}